package com.borrowed.book.book.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.borrowed.book.book.Exception.UnderStockException;
import com.borrowed.book.book.domain.*;
import com.borrowed.book.book.mapper.SBookMapper;
import com.borrowed.book.book.mapper.SGroupMapper;
import com.borrowed.book.book.mapper.SLabelMapper;
import com.borrowed.book.book.service.SBookService;
import com.borrowed.book.system.domain.AjaxResult;
import com.borrowed.book.system.util.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;


@Service
public class SBookServiceImpl implements SBookService {
    @Autowired
    private SGroupMapper groupMapper;
    @Autowired
    private SLabelMapper labelMapper;
    @Autowired
    private SBookMapper  bookMapper;

    @Override
    public int insertGroup(SGroup record) {
        record.setCreateTime(new Date());
        return groupMapper.insert(record);
    }

    @Override
    public int updateGroup(SGroup record) {
        record.setUpdateTime(new Date());
        return groupMapper.update(record);
    }

    @Override
    public AjaxResult deleteGroup(Long id) {
        Integer bookCount=groupMapper.selectBookCountByGroupId(id);
        if(bookCount>0){
            return AjaxResult.error("分组存在关联图书，删除失败");
        }else{
            groupMapper.delete(id);
            return AjaxResult.sucess();
        }
    }

    @Override
    public List<SGroup> selectGroupList() {
        List<SGroup> groupList=groupMapper.selectGroupList();
        return groupList;
    }

    @Override
    public int insertLabel(SLabel label) {
        label.setCreateTime(new Date());
        return labelMapper.insert(label);
    }

    @Override
    public AjaxResult deleteBookLabelRel(Long id) {
        labelMapper.deleteLabel(id);
        labelMapper.deleteBookLabelRel(id);
        return AjaxResult.sucess();
    }

    @Override
    public List<SLabel> selectLabelList() {
        List<SLabel> labelList=labelMapper.selectLabelList();
        return labelList;
    }

    @Override
    public void addBook(SBook book) {
        book.setCreateTime(new Date());
        book.setRemainingNumber(book.getNumber());
        book.setDeleteFlag(0);
        bookMapper.insert(book);
        Long bookId=book.getId();
        //插入书籍标签关联关系
        AddBookLabelRel(bookId,book.getLabels());
    }

    @Override
    public void updateBookInfo(SBook book) {
        //计算剩余借阅数量=原剩余借阅数量+新数量-原数量
        SelectBookOutDto originalBook=bookMapper.selectBookById(book.getId());

        book.setUpdateTime(new Date());
            book.setRemainingNumber(originalBook.getRemainingNumber()+book.getNumber()-originalBook.getNumber());
        bookMapper.update(book);
        //删除标签关联关系
        bookMapper.deleteBookLabelRel(book.getId());
        //插入书籍标签关联关系
        Long bookId=book.getId();
        AddBookLabelRel(bookId,book.getLabels());
    }

    @Override
    public void deleteBookById(Long id) {
        Map<String,Object> map=new HashMap<>();
        List<Long> ids=new ArrayList<>();
        ids.add(id);
        map.put("ids",ids);
        bookMapper.deleteBookByIds(map);
        //删除标签关联关系
        bookMapper.deleteBookLabelRel(id);
    }

    @Override
    public void deleteBookByIds(CommonIds ids) {
        Map<String,Object> map=new HashMap<>();
        map.put("ids",ids.getIds());
        bookMapper.deleteBookByIds(map);
        //删除标签关联关系
        bookMapper.deleteBookLabelRels(map);
    }

    @Override
    public List<SelectBookOutDto> selectBookList(SelectBookInDto inDto) throws UnsupportedEncodingException {
        //将中文字符重新编码 默认编码问 ISO-8859-1

        Map<String,Object>  param=new HashMap<>();
        param.put("bookName",inDto.getBookName());
        param.put("isbn",inDto.getIsbn());
        param.put("labelId",inDto.getLabelId());
        param.put("author",inDto.getAuthor());
        List<SelectBookOutDto>  bookList=bookMapper.selectBookList(param);

        return bookList;
    }

    @Override
    public SelectBookOutDto selectBookDetailById(Long id) {
        SelectBookOutDto book=bookMapper.selectBookById(id);
        return book;
    }

    @Override
    public String selectIsbnBookInfo(String isbn) throws IOException {
        //请求URL
        HttpGet httpGet = new HttpGet("https://api.zuk.pw/situ/book/isbn/"+isbn);
        StringEntity entity = new StringEntity("");
        entity.setContentType("application/json");

        //完成签名并执行请求
        String result = "";
        // *********************** 此处有坑 (CloseableHttpResponse)  与文档有出入，这样写可用
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpGet);
        JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }

    /**
     * 根据isbn检查图书是否存在，若存在，数量和库存+1，不存在返回false
     * @param isbn
     * @return
     */
    @Override
    public String checkIsbnBookInfo(String isbn) {
        SBook bookInfo=bookMapper.selectBookByIsbn(isbn);
        if(bookInfo==null){
            return "false";
        }else{
            //书籍库存增加1
            bookMapper.increaseBookNumber(bookInfo.getId());
            return "true";
        }
    }


    /**
     * 插入书籍标签关联关系
     * @param bookId  图书id
     * @param labelIdsStr  标签，多个以逗号隔开
     */
    public void  AddBookLabelRel(Long bookId,String labelIdsStr){
        //插入书籍标签关联关系
        if(StringUtils.isNotEmpty(labelIdsStr)){
            String[] labelIds=labelIdsStr.split(",");
            Map<String,Object> paramMap=new HashMap<>();
            paramMap.put("bookId",bookId);
            for(int i=0;i<labelIds.length;i++){
                paramMap.put("labelId",labelIds[i]);
                bookMapper.insertBookLabelRel(paramMap);
            }
        }
    }

    /**
     * 检查图书库存是否充足
     * @param bookId
     */
    @Override
    public SelectBookOutDto CheckBookRemaining(Long bookId) throws UnderStockException {
        SelectBookOutDto  bookInfo=bookMapper.selectBookById(bookId);
        if(bookInfo.getRemainingNumber()<=0){
            throw new UnderStockException("《"+bookInfo.getBookName()+"》库存不足，请重新选择");
        }
        return  bookInfo;
    }
}
